'use strict'

const { Controller } = require('egg')

class LabelController extends Controller {
  // 获取全部标签
  async getLabel() {
    const { ctx, app } = this
    // 参数验证
    ctx.validate({
      name: { type: 'string', desc: '标签名称' },
      wall_id: { type: 'int', desc: '墙的id' }
    })
    const { name, wall_id } = ctx.request.query
    const Op = app.Sequelize.Op
    // 整理查询条件
    let where = {}
    if (name) where.name = { [Op.like]: `%${name}%` }
    if (wall_id) where.wall_id = wall_id

    let result = await app.model.Label.findAll({
      where,
      include: [{ model: app.model.Wall, attributes: ['title'] }],
      order: [['id', 'DESC']]
    })
    // 获取标签下留言的数量
    result = JSON.parse(JSON.stringify(result))
    for (let i = 0; i < result.length; i++) {
      result[i].leaveword_count = await app.model.Leaveword.count({
        where: { label_id: result[i].id }
      })
    }
    ctx.apiSuccess(result)
  }
  // 新增标签
  async createLabel() {
    const { ctx, service } = this
    // 参数验证
    ctx.validate({
      wall_id: { type: 'int', required: true, desc: '墙的id' },
      name: { type: 'string', required: true, range: { min: 1, max: 30 }, desc: '标签名称' }
    })
    const { wall_id, name } = ctx.request.body
    const result = await service.label.createLabel(wall_id, name)
    ctx.apiSuccess(result)
  }
  // 修改标签
  async updateLabel() {
    const { ctx, app } = this
    // 参数验证
    ctx.validate({
      id: { type: 'int', required: true, desc: '标签id' },
      name: { type: 'string', required: true, range: { min: 1, max: 30 }, desc: '标签名称' }
    })
    const { id, name } = ctx.request.body
    // 查询数据库
    const label = await app.model.Label.findOne({ where: { id } })
    if (!label) ctx.throw(400, '该记录不存在')
    const result = await label.update({ name })

    ctx.apiSuccess(result)
  }
  // 删除标签
  async deleteLabel() {
    const { ctx, app } = this
    // 参数验证
    ctx.validate({
      ids: { type: 'string', required: true, desc: '标签id' }
    })
    let { ids } = ctx.request.body
    // 整理参数
    ids = ids.split(',').map((id) => parseInt(id))
    const result = await app.model.Label.destroy({ where: { id: ids } })

    ctx.apiSuccess(result)
  }
}

module.exports = LabelController
